package www.dashu.com.controller;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;
import www.dashu.com.api.CommonResult;
import www.dashu.com.domain.CProductAttribute;
import www.dashu.com.domain.CProductAttributeValue;
import www.dashu.com.service.CProductAttributeService;
import www.dashu.com.service.CProductAttributeValueService;
import www.dashu.com.service.RedisService;
import www.dashu.com.domain.CProduct;
import www.dashu.com.dto.CProductQuery;
import www.dashu.com.service.CProductService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;
import java.util.stream.Collectors;

@Controller
@Api(tags = "CProductController", description = "商品信息")
@RequestMapping("/product")
public class CProductController
{

    @Autowired
    CProductService productService;
    @Autowired
    RedisService redisService;
    @Autowired
    CProductAttributeValueService attributeValueService;
    @Autowired
    CProductAttributeService attributeService;

    @ApiOperation(value = "商品信息列表")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<Page<CProduct>> list(CProductQuery query) {

        try {
            Page<CProduct> pageData = productService.findAll(query);
            pageData.getContent().forEach(cProduct -> {
                List<CProductAttribute> attributeList = new ArrayList<>();

                Map<String, Object> queryMap = new HashMap<>();
                queryMap.put("productId", cProduct.getId());
                List<CProductAttributeValue> attributeValueList = attributeValueService.findAll(queryMap);

                if(null != attributeValueList){
                    attributeValueList.forEach(attribute ->{
                        CProductAttribute attr = attributeService.findById(attribute.getProductAttributeId()).get();
                        attr.setProductId(cProduct.getId());
                        attr.setValues(Arrays.asList(attribute.getValue().split(",")));
                        if(!StringUtils.isEmpty(attribute.getOprations())){
                            attr.setOptions(JSON.parseArray(attribute.getOprations()));
                        }else {
                            attr.setOptions(new ArrayList<>());
                        }
                        CProductAttribute attrTarget = new CProductAttribute();
                        BeanUtils.copyProperties(attr, attrTarget);
                        attributeList.add(attrTarget);
                    });
                }

                cProduct.setSelectProductAttr(attributeList);
            });
            return CommonResult.success(pageData);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @ApiOperation(value = "新增商品信息")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult create(@RequestBody CProduct product) {
        product.setId(productService.createId(product));

        product.setCreateTime(new Date());
        product.setUpdateTime(new Date());

        productService.save(product);
        return CommonResult.success();
    }

    @ApiOperation(value = "修改商品信息")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor = Exception.class)
    public CommonResult update(@RequestBody CProduct product) {
        List<CProductAttribute> attrs = product.getSelectProductAttr();
        List<CProductAttributeValue> attributeValueList = new ArrayList<>();
        if(!StringUtils.isEmpty(attrs)){
            attributeValueService.deleteByProductId(product.getId());
            attrs.forEach(attr ->{
                CProductAttributeValue attributeValue = new CProductAttributeValue();
                attributeValue.setId(attributeValueService.createId(attributeValue));
                attributeValue.setProductId(product.getId());
                attributeValue.setProductAttributeId(attr.getId());
                attributeValue.setValue(attr.getValues().stream().collect(Collectors.joining(",")));
                if(attr.getInputType() == 0){//0手工输入
                    attributeValue.setOprations(JSON.toJSONString(attr.getOptions()));
                }
                attributeValueList.add(attributeValue);
            });
            attributeValueService.saveAll(attributeValueList);
        }

        product.setUpdateTime(new Date());
        productService.save(product);
        return CommonResult.success();
    }

    @ApiOperation(value = "删除商品信息")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor = Exception.class)
    public CommonResult delete(@RequestBody CProduct product) {
        productService.deleteById(product.getId());
        return CommonResult.success();
    }

}
